package com.xiaoxu.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoxu.base.exception.bkSchoolException;
import com.xiaoxu.content.dao.CourseTeacherMapper;
import com.xiaoxu.content.model.po.CourseTeacher;
import com.xiaoxu.content.service.CourseTeacherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 课程-教师关系表 服务实现类
 * </p>
 *
 * @author xiaoxu
 */
@Slf4j
@Service
public class CourseTeacherServiceImpl extends ServiceImpl<CourseTeacherMapper, CourseTeacher> implements CourseTeacherService {

    private final CourseTeacherMapper courseTeacherMapper;

    public CourseTeacherServiceImpl(CourseTeacherMapper courseTeacherMapper){
        this.courseTeacherMapper=courseTeacherMapper;
    }

    /**
     * 根据课程Id查询课程师资信息
     * @param courseId 课程Id
     * @return List<CourseTeacher>
     */
    @Override
    public  List<CourseTeacher> findCourseTeacherList(Long courseId) {
        LambdaQueryWrapper<CourseTeacher> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(courseId!=null,CourseTeacher::getCourseId,courseId);
        List<CourseTeacher> courseTeachers = courseTeacherMapper.selectList(queryWrapper);
        if (courseTeachers==null){
            throw new bkSchoolException("业务异常,未找到该课程所教学的教师，如未发现异常，请联系管理员");
        }
        return courseTeachers;
    }

    /**
     * 新增或修改课程的师资信息
     * @param courseTeacher 课程教师信息
     */
    @Override
    @Transactional
    public void saveOrUpdateCourseTeacher(CourseTeacher courseTeacher) {
        Long id = courseTeacher.getId();
        CourseTeacher teacher = courseTeacherMapper.selectById(id);
        int ResultCount;
        if (teacher == null){
            //插入
            courseTeacher.setCreateDate(LocalDateTime.now());
            ResultCount = courseTeacherMapper.insert(courseTeacher);
        }else{
            //修改
            BeanUtils.copyProperties(courseTeacher,teacher);
            ResultCount = courseTeacherMapper.updateById(teacher);
        }
        if (ResultCount <=0){
            throw new bkSchoolException("业务异常,添加教师失败，如未发现异常，请联系管理员");
        }
    }

    /**
     * 根据教师Id删除课程的师资
     * @param courseId 课程Id
     * @param teacherId 教师Id
     */
    @Override
    @Transactional
    public void deleteCourseTeacher(Long courseId, Long teacherId) {
        CourseTeacher teacher = courseTeacherMapper.selectById(teacherId);
        if (!courseId.equals(teacher.getCourseId())){
            throw new bkSchoolException("业务异常，该教师不在该课程下");
        }
        int ResultCount = courseTeacherMapper.deleteById(teacherId);
        if (ResultCount <=0){
            throw new bkSchoolException("业务异常，删除教师失败");
        }
    }
}
